package com.fh.shop.admin.biz.product;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fh.shop.admin.common.DataTableResult;
import com.fh.shop.admin.common.ServerResponse;
import com.fh.shop.admin.mapper.product.IProductImageMapper;
import com.fh.shop.admin.mapper.product.IProductMapper;
import com.fh.shop.admin.po.product.Product;
import com.fh.shop.admin.po.product.ProductImage;
import com.fh.shop.admin.vo.product.ProductVo;
import com.fh.shop.admin.param.product.ProductAddParam;
import com.fh.shop.admin.param.product.ProductQueryParam;
import com.fh.shop.admin.param.product.ProductUpdateParam;
import com.fh.shop.admin.util.OSSUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service("productService")
public class IProductServiceImpl implements IProductService {
    @Autowired
    private IProductMapper productMapper;

    @Autowired
    private IProductImageMapper productImageMapper;

    @Override
    public ServerResponse addProduct(ProductAddParam productAddParam) {
        //添加商品
        Product product = productAddParam.getProduct();
        productMapper.insert(product);

        //添加子图
        String imagePath = productAddParam.getImagePath();

        if (StringUtils.isNotEmpty(imagePath)){
            /*Arrays.stream(imagePath.split(",")).forEach(x -> {
                ProductImage productImage = new ProductImage();
                productImage.setProductId(product.getId());
                productImage.setImagePath(x);
                productImageMapper.insert(productImage);
            });*/

            List<ProductImage> productImageList = Arrays.stream(imagePath.split(",")).map(x -> {
                ProductImage productImage = new ProductImage();
                productImage.setProductId(product.getId());
                productImage.setImagePath(x);
                return productImage;
            }).collect(Collectors.toList());
            productImageMapper.addProductImage(productImageList);
        }

        return ServerResponse.success();
    }

    @Override
    public DataTableResult findProductList(ProductQueryParam productQueryParam) {
        Long count = productMapper.findCount(productQueryParam);
        List<Product> productList = productMapper.findProductList(productQueryParam);
        return new DataTableResult(productQueryParam.getDraw(),count,count,productList);
    }

    @Override
    public ServerResponse deleteProduct(Long id,String root) {
        //查询商品表
        Product product = productMapper.selectById(id);

        //查询子图表
        QueryWrapper<ProductImage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("productId",id);
        List<ProductImage> productImages = productImageMapper.selectList(queryWrapper);

        //删除商品表
        productMapper.deleteById(id);

        //删除子图表
        productImageMapper.delete(queryWrapper);

        //删除本地主图
//        deleteImg(root, product.getMainImage());
        OSSUtil.deleteFile(product.getMainImage());

        //删除本地子图
        /*productImages.forEach(x -> {
            deleteImg(root,x.getImagePath());
        });*/
        List<String> imgPaths = productImages.stream().map(x -> x.getImagePath()).collect(Collectors.toList());
        //调用批量删除oss文件的方法
        OSSUtil.deleteBatchFile(imgPaths);

        return ServerResponse.success();
    }

    @Override
    public ServerResponse deleteBatch(String ids, String root) {
        if (StringUtils.isNotEmpty(ids)){
            List<Long> idList = Arrays.stream(ids.split(",")).map(x -> Long.parseLong(x)).collect(Collectors.toList());
            //查询商品表
            List<Product> products = productMapper.selectBatchIds(idList);

            //查询子图表
            QueryWrapper<ProductImage> productImageQueryWrapper = new QueryWrapper<>();
            productImageQueryWrapper.in("productId",idList);
            List<ProductImage> productImages = productImageMapper.selectList(productImageQueryWrapper);

            //删除商品表
            productMapper.deleteBatchIds(idList);

            //删除子图表
            productImageMapper.delete(productImageQueryWrapper);

            //删除本地主图
            /*products.forEach(x -> {
                deleteImg(root,x.getMainImage());
            });*/
            List<String> mainPaths = products.stream().map(x -> x.getMainImage()).collect(Collectors.toList());
            OSSUtil.deleteBatchFile(mainPaths);

            //删除本地子图
            /*productImages.forEach(x -> {
                deleteImg(root,x.getImagePath());
            });*/
            List<String> imagePaths = productImages.stream().map(x -> x.getImagePath()).collect(Collectors.toList());
            OSSUtil.deleteBatchFile(imagePaths);

        }
        return ServerResponse.success();
    }

    @Override
    public ServerResponse findProduct(Long id) {

        //查询商品表
        Product product = productMapper.selectById(id);

        /*//获得分类
        String cate1 = null;
        String cate2 = null;
        String cate3 = null;
        try {
            cate1 = cateMapper.selectById(product.getCate1()).getCateName();
            cate2 = cateMapper.selectById(product.getCate2()).getCateName();
            cate3 = cateMapper.selectById(product.getCate3()).getCateName();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (cate2 == null){
            product.setCateName(cate1);
        } else if(cate3 == null){
            product.setCateName(cate1+"-"+cate2);
        }else {
            product.setCateName(cate1+"-"+cate2+"-"+cate3);
        }*/


        //查询子图表
        QueryWrapper<ProductImage> productImageQueryWrapper = new QueryWrapper<>();
        productImageQueryWrapper.eq("productId",id);
        List<ProductImage> productImages = productImageMapper.selectList(productImageQueryWrapper);

        //组装数据
        ProductVo productVo = new ProductVo();
        productVo.setProduct(product);
        productVo.setProductImageList(productImages);

        return ServerResponse.success(productVo);
    }

    //回显删除子图
    @Override
    public ServerResponse deleteImage(Long key, String root) {
        //查询子图
        ProductImage productImage = productImageMapper.selectById(key);
        //删除子图
        productImageMapper.deleteById(productImage.getId());
        //删除硬盘上的子图
//        deleteImg(root, productImage.getImagePath());
        OSSUtil.deleteFile(productImage.getImagePath());
        return ServerResponse.success();
    }

    @Override
    public ServerResponse updateProduct(ProductUpdateParam productUpdateParam, String root) {
        //修改商品
        //判断是否修改了主图
        Product product = productUpdateParam.getProduct();
        String oldMainImg = productUpdateParam.getOldMainImg();
        Long id = product.getId();
        if (StringUtils.isNotEmpty(product.getMainImage())){
            //不为空说明新图有值,那么直接放入新值
            product.setMainImage(product.getMainImage());
            //删除本地的老图片
//            deleteImg(root,oldMainImg);
            OSSUtil.deleteFile(oldMainImg);
        }else {
            //否则将老图的值放入
            product.setMainImage(oldMainImg);
        }
        productMapper.updateById(product);

        //修改子图
        String imagePath = productUpdateParam.getImagePath();
        if (StringUtils.isNotEmpty(imagePath)){
            //第一种方式
            /*Arrays.stream(imagePath.split(",")).forEach(x -> {
                ProductImage productImage = new ProductImage();
                productImage.setImagePath(x);
                productImage.setProductId(id);
                productImageMapper.insert(productImage);
            });*/

            //第二种方式
            /*List<ProductImage> productImageList = new ArrayList<>();
            Arrays.stream(imagePath.split(",")).forEach(x -> {
                ProductImage productImage = new ProductImage();
                productImage.setImagePath(x);
                productImage.setProductId(id);
                productImageList.add(productImage);
            });*/

            //第三种方式
            List<ProductImage> productImageList = Arrays.stream(imagePath.split(",")).map(x -> {
                ProductImage productImage = new ProductImage();
                productImage.setImagePath(x);
                productImage.setProductId(id);
                return productImage;
            }).collect(Collectors.toList());
            productImageMapper.addProductImage(productImageList);

        }

        return ServerResponse.success();
    }

    @Override
    public ServerResponse updateState(Long id, Integer state, String flag) {
        Product product = new Product();
        product.setId(id);
        if (flag.equals("status")){
            product.setStatus(state);
        }else if (flag.equals("recommend")){
            product.setRecommend(state);
        }else if (flag.equals("newProduct")){
            product.setNewProduct(state);
        }
        productMapper.updateById(product);
        return ServerResponse.success();
    }


    //封装删除本地图片
    private void deleteImg(String root, String filePath) {
        String realPath = root + filePath;
        File file = new File(realPath);
        if (file.exists()){
            file.delete();
        }
    }

}
